import React, { useState, useEffect, useMemo } from 'react';
import Joyride, { STATUS } from 'react-joyride';
import { useRouter } from '@/router/hooks';
import { useLocation } from 'react-router-dom';

import { useTourActions, useIsTourStart, useIsTourGuide, useIsFirstLogin } from '@/store/tourStore';

import { useConfig } from '@/store/configStore';

import { Button, Modal } from 'antd';
import useWindowWidth from '@/hooks/event/use-window-width';
import { SvgIcon } from '@/components/icon';

import { RightOutlined } from '@ant-design/icons';
import usePermission from '@/hooks/event/usePermission';
import { useTranslation } from 'react-i18next';

import './style.css';

const JoyrideGuide = React.memo(() => {
  const { t } = useTranslation();

  const [isRunning, setIsRunning] = useState(false);
  const [stepIndex, setStepIndex] = useState(0);
  // const isAdmin  = false;
  const { isAdmin } = usePermission();
  const [currentPage, setCurrentPage] = useState('/homepage');
  const router = useRouter();
  const location = useLocation();
  const isTourStart = useIsTourStart();
  const isTourGuide = useIsTourGuide();
  const isFirstLogin = useIsFirstLogin();
  const { id } = useConfig();
  const { setIsTourStart, setIsUserClick, setIsFirstLogin, setIsTourGuide } = useTourActions();
  const { isPc } = useWindowWidth();


  useEffect(() => {
    // !isTourStart && isFirstLogin && setIsTourGuide(isFirstLogin);
  }, [isFirstLogin]);

  useEffect(() => {
    setStepIndex(0);
    setIsRunning(isTourStart);
  }, [isTourStart]);

  const endJoyride = () => {
    setIsRunning(false);
    setIsTourStart(false);
    setIsUserClick(false);
    setIsFirstLogin(false);
    router.push('/homepage');
  };

  const handleJoyrideCallback = (data: any) => {
    const { type, status, action, index } = data;
    console.log(type, status, action, index);

    if (index == 3 && action == 'prev') {
      router.pushQuery('/homepage', {
        index,
        action
      });
    }

    if (index == 4 && action == 'prev') {
      router.pushQuery('/management', {
        index,
        action,
      });
    }

    if (index == 4 && action == 'next') {
      router.pushQuery('/management', {
        index,
        action
      });
    }

    if (index == 5 && action == 'next') {
      router.pushQuery(`/apps/manage/${id}`, {
        index,
        action,
      });
    }

    if (type === 'step:after' && action === 'next') {
      setStepIndex(index + 1);
    }

    if (type === 'step:after' && action === 'prev') {
      setStepIndex(index - 1);
    }

    if ([STATUS.FINISHED, STATUS.SKIPPED].includes(status)) {
      endJoyride();
    }

    if (action == 'close') {
      endJoyride();
    }
  };

  const handleJoyrideCallback2 = (data: any) => {
    const { type, status, action, index } = data;
    console.log(type, status, action, index);

    if (type === 'step:after' && action === 'next') {
      setStepIndex(index + 1);
      if (index == 1) {
        setIsUserClick(true)
      }
    }

    if (type === 'step:after' && action === 'prev') {
      setStepIndex(index - 1);
      if (index == 2) {
        setIsUserClick(false);
      }
    }

    if ([STATUS.FINISHED, STATUS.SKIPPED].includes(status)) {
      endJoyride();
    }

    if (action == 'close') {
      endJoyride();
    }
  };

  useEffect(() => {
    console.log('Route changed:', location.pathname, stepIndex);
    const { state } = location;
    if (location.pathname == '/homepage' && state?.action) {
      setStepIndex(3);
    }
    if (location.pathname == '/management' && state?.action) {
      setStepIndex(4);
    }
    if (location.pathname == `/apps/manage/${id}` && state?.action) {
      setStepIndex(5);
    }
  }, [location.pathname]);

  const joyrideLocale = {
    back: t('page.homePage.prev'),
    close: t('page.homePage.close'),
    last: t('page.homePage.last'),
    next: t('page.homePage.next'),
    skip: t('page.homePage.skip'),
  };

  const steps2 = useMemo(
    () => [
      {
        target: '.jr-step-1',
        content: (
          <div>
            {t('page.homePage.jrStepText-1.1')}
            {/* 您好，欢迎在这里输入问题 */}
            <br />
            {t('page.homePage.jrStepText-1.2')}
            {/* 向我提问，回车即可得到答案 */}
          </div>
        ),
        placement: 'top',
        disableBeacon: true,
        page: '/homepage',
        index: 1,
      },
      {
        target: '.jr-step-2',
        content: (
          <div>
            {t('page.homePage.jrStepText-2.1')}

            {/* 点击应用导航，体验不同产品功能 */}
            <br />
            {t('page.homePage.jrStepText-2.2')}

            {/* 支持新建对话，查看历史对话等 */}
          </div>
        ),
        // content: '应用导航，支持新建会话，查看历史会话等。',
        placement: 'right',
        disableBeacon: true,
        page: '/homepage',
        index: 2,
      },
      {
        target: '.jr-step-3-mobile',
        content: <div> {t('page.homePage.jrStepText-3')}</div>,
        placement: 'right',
        disableBeacon: true,
        page: '/homepage',
        index: 3,
      },
      {
        target: '.jr-step-4-mobile',
        content: <div> {t('page.homePage.jrStepText-4')}</div>,
        placement: 'right',
        disableBeacon: true,
        page: '/homepage',
        index: 4,
      },
    ],
    [],
  );

  const steps1 = useMemo(
    () => [
      {
        target: '.jr-step-1',
        content: (
          <div>
            {t('page.homePage.jrStepText-1.1')}

            <br />
            {t('page.homePage.jrStepText-1.2')}
          </div>
        ),
        placement: 'top',
        disableBeacon: true,
        page: '/homepage',
        index: 1,
      },
      {
        target: '.jr-step-2',
        content: (
          <div>
            {t('page.homePage.jrStepText-2.1')}

            <br />
            {t('page.homePage.jrStepText-2.2')}
          </div>
        ),
        // content: '应用导航，支持新建会话，查看历史会话等。',
        placement: 'right',
        disableBeacon: true,
        page: '/homepage',
        index: 2,
      },
      {
        target: '.jr-step-3',
        content: (
          <div>
            {t('page.homePage.jrStepText-3.1-v2')}

            <br />
            {t('page.homePage.jrStepText-3.2-v2')}

            <br />
            {t('page.homePage.jrStepText-3.3-v2')}
          </div>
        ),
        placement: 'bottom',
        disableBeacon: true,
        page: '/homepage',
        index: 3,
      },
      {
        target: '.jr-step-4',
        content: t('page.homePage.jrStepText-4-v2'),
        placement: 'right',
        disableBeacon: true,
        page: '/homepage',
        index: 4,
      },
      {
        target: '.jr-step-5',
        content: t('page.homePage.jrStepText-5'),
        placement: 'top',
        disableBeacon: true,
        page: '/management',
        index: 5,
      },
      {
        target: '.jr-step-6',
        content: t('page.homePage.jrStepText-6'),
        placement: 'bottom',
        disableBeacon: true,
        page: `/apps/manage/${id}`,
        index: 6,
      },
      {
        target: '.jr-step-7',
        content: (
          <div>
            {t('page.homePage.jrStepText-7.1')}

            <br />
            {t('page.homePage.jrStepText-7.2')}
          </div>
        ),
        placement: 'top',
        disableBeacon: true,
        page: `/apps/manage/${id}`,
        index: 7,
      },
    ],
    [],
  );

  const steps = isAdmin ? steps1 : steps2;

  const renderTooltip = ({
    continuous,
    index,
    step,
    backProps,
    primaryProps,
    tooltipProps,
    skipProps,
  }) => {
    return (
      <div
        {...tooltipProps}
        style={{ backgroundColor: '#fff', padding: '16px', borderRadius: '10px' }}
      >
        {/* <div 
          
          style={{
          backgroundColor:'#e3e1ff', color:'#6159d3', padding:'5px 0', 
          width: isPc?'550px':'unset',
          height: '130px', borderRadius: '7px', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
            <SvgIcon
              icon='rj-guide-left'
              size={125}
              style={{
                padding: '3px',
              }}
            />
            {step.content}
            <SvgIcon
              icon='rj-guide-right'
              size={125}
              style={{
                padding: '3px',
              }}
            />
          </div> */}

        <div
          style={{
            backgroundColor: '#e3e1ff',
            color: '#6159d3',
            padding: isPc ? '5px 0' : '5px 50px',
            width: isPc ? '550px' : 'unset',
            minWidth: '300px',
            maxWidth: '100%',
            height: '130px',
            borderRadius: '7px',
            display: 'flex',
            fontSize: isPc ? '16px' : '14px',
            alignItems: 'center',
            justifyContent: 'center',
            position: 'relative',
          }}
        >
          <SvgIcon
            icon="rj-guide-left"
            size={125}
            style={{
              padding: '3px',
              position: 'absolute', // 绝对定位
              left: '-30', // 置于左侧
              top: '50%', // 垂直居中
              transform: 'translateY(-50%)', // 垂直居中
              zIndex: 1, // 置于文字下方
            }}
          />
          {step.content}
          <SvgIcon
            icon="rj-guide-right"
            size={125}
            style={{
              padding: '3px',
              position: 'absolute', // 绝对定位
              right: '-30', // 置于右侧
              top: '50%', // 垂直居中
              transform: 'translateY(-50%)', // 垂直居中
              zIndex: 1, // 置于文字下方
            }}
          />
        </div>

        <div
          style={{
            display: 'flex',
            gap: '8px',
            marginTop: '16px',
            justifyContent: step.index != steps.length ? 'space-between' : 'end',
          }}
        >
          {step.index != steps?.length && (
            <Button {...skipProps} type="text" style={{ color: '#808080' }}>
              {t('page.homePage.skip')}
            </Button>
          )}
          <div style={{ display: 'flex' }}>
            {step.index == 1 ? null : (
              <Button type="text" {...backProps} style={{ color: '#808080' }}>
                {t('page.homePage.back')}
              </Button>
            )}
            <div
              style={{
                fontSize: '12px',
                color: '#808080',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                margin: '0 10px',
              }}
            >
              {`第 `}
              <span style={{ color: '#bb5bff' }}>{step?.index}</span>
              {`/${steps?.length}`}
            </div>
            <Button {...primaryProps} style={{ backgroundColor: '#bb5bff', color: '#fff' }}>
              {step.index == steps?.length ? t('page.homePage.last') : t('page.homePage.next')}
              {step.index != steps?.length && <RightOutlined />}
            </Button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <>
      <Modal
        className="guide-modal"
        centered
        title=""
        closable={false}
        open={false}
        onOk={() => {
          setIsTourGuide(false);
          setIsTourStart(true);
        }}
        onCancel={() => {
          setIsTourGuide(false);
        }}
        footer={[
          <div
            key="footer"
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              padding: '0',
              width: '100%',
            }}
          >
            <Button
              key="cancel"
              type="text"
              style={{ color: '#808080' }}
              onClick={() => {
                setIsTourGuide(false);
                setIsFirstLogin(false)
              }}
            >
              {t('page.homePage.no')}
            </Button>
            <Button
              key="next"
              type="primary"
              style={{ backgroundColor: '#bb5bff', color: '#fff' }}
              onClick={() => {
                setIsTourGuide(false);
                setIsTourStart(true);
              }}
            >
              {t('page.homePage.next')}

              <RightOutlined />
            </Button>
          </div>,
        ]}
      >
        <div
          className="flex items-center justify-center"
          style={{
            height: '130px',
            backgroundColor: '#e3e1ff',
            color: '#6159d3',
            padding: isPc ? '5px 0' : '5px 50px',
            width: isPc ? '550px' : 'unset',
            fontSize: isPc ? '16px' : '14px',
            minWidth: '300px',
            maxWidth: '100%',
            borderRadius: '7px',
            display: 'flex',
            position: 'relative',
          }}
        >
          <SvgIcon
            icon="rj-guide-left"
            size={125}
            style={{
              padding: '3px',
              position: 'absolute', // 绝对定位
              left: '-30', // 置于左侧
              top: '50%', // 垂直居中
              transform: 'translateY(-50%)', // 垂直居中
              zIndex: 1, // 置于文字下方
            }}
          />
          {t('page.homePage.jrStepText-0.1')}
          <br />
          {t('page.homePage.jrStepText-0.2')}

          <SvgIcon
            icon="rj-guide-right"
            size={125}
            style={{
              padding: '3px',
              position: 'absolute', // 绝对定位
              right: '-30', // 置于右侧
              top: '50%', // 垂直居中
              transform: 'translateY(-50%)', // 垂直居中
              zIndex: 1, // 置于文字下方
            }}
          />
        </div>
      </Modal>
      <Joyride
        steps={steps}
        callback={isAdmin ? handleJoyrideCallback : handleJoyrideCallback2}
        stepIndex={stepIndex}
        disableOverlayClose={true}
        run={isRunning}
        locale={joyrideLocale}
        continuous={true}
        disableCloseOnEsc={true}
        tooltipComponent={renderTooltip}
        // showSkipButton={true}
        // showCloseButton={true}
        showSkipButton={false} // 禁用默认的跳过按钮
        showCloseButton={false} // 禁用默认的关闭按钮
        styles={{
          options: {
            zIndex: 10000,
          },
        }}
      />
    </>
  );
});

export default JoyrideGuide;
